<?php
	/**
	 * Template type.
	 * @author IMP
	 */

	function tpl_include(File $__FILE__, array $_ = array()){
		extract($_, EXTR_OVERWRITE);
		unset($_);
		
		include $__FILE__;
	}
	
	function publicURL($path = ''){
		return URL_PUBLIC . '/' . $path;
	}
	
	class Template extends ArrayIterator implements Emittable, Resource {
		private $file;
		
		public function __construct(File $f, array $variables = array()){
			parent::__construct($variables);
			$this->file = $f;
		}
		
		public function emit(OutputBuffer &$ob = null){
			if($ob == null){
				ErrorCatcher::beginCatching();
				
				$dob = new OutputBuffer();
				tpl_include($this->file, $this->getArrayCopy());
				$dob->close();
				
				if(ErrorCatcher::caughtErrors()){
					foreach(ErrorCatcher::grabErrors() as $e){
						throw new TemplateException($e['message'], $e['code'], $e['file'], $e['line']);
					}
				}else{
					ErrorCatcher::grabErrors();
					return $dob->getContents();
				}
			}else{
				ErrorCatcher::beginCatching();
				
				tpl_include($this->file, $this->getArrayCopy());
				
				if(ErrorCatcher::caughtErrors()){
					foreach(ErrorCatcher::grabErrors() as $e){
						throw new TemplateException($e['message'], $e['code'], $e['file'], $e['line']);
					}
				}else{
					ErrorCatcher::grabErrors();
					return $ob->getContents();
				}
			}
		}
		
		public function __toString(){
			return $this->emit();
		}
		
		public function save(File $f){
			if($this->file->getAbsolutePath() != $f->getAbsolutePath()){
				$f->write($this->file->read());
			}
		}
		
		public static function formFilename($name){
			return $name . '.tpl';
		}
		
		public static function open(File $f){
			return new self($f);
		}
	}
?>